import 'dart:io';

import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module/module_create_wallet/pages/set_pass_page.dart';
import 'package:aichat_flutter_wallet/module/module_wallet/pages/wallet_mpc_securitymanager.dart';
import 'package:aichat_flutter_wallet/module/module_wallet_manage/widgets/delete_wallet.dart';
import 'package:aichat_flutter_wallet/module_common/bridge/native_channel_bridge.dart';
import 'package:aichat_flutter_wallet/module_common/mpc_help/mpcManager.dart';
import 'package:aichat_flutter_wallet/module_common/network/http_api.dart';
import 'package:aichat_flutter_wallet/module_common/provider/nav_key.dart';
import 'package:aichat_flutter_wallet/module_common/provider/wallet_info_provider.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/kai_bottom_tip_dialog.dart';
import 'package:flutter/material.dart';
import 'package:lib_apple_auth_storage/lib_apple_auth_storage.dart';
import 'package:lib_cloud_storage/lib_cloud_storage.dart';
import 'package:lib_cloud_storage/lib_cloud_storage_platform_interface.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_network/lib_network.dart';
import 'package:http/http.dart' as http;
import 'package:lib_util/lib_util.dart';
import 'package:lib_web3/lib_solana_web3.dart';
import 'package:lib_web3/lib_tron_web3.dart';
import 'package:lib_web3/lib_web3_method.dart';

import '../network/http_chain_list.dart';

extension ListExtension<T> on List<T> {
  T? firstWhereOrNull(bool Function(T) test) {
    for (var element in this) {
      if (test(element)) {
        return element;
      }
    }
    return null;
  }
}

class NodeRateUtils {
  static Color slowColor = Color.fromRGBO(224, 66, 28, 1);
  static Color mediumColor = Color.fromRGBO(255, 164, 26, 1);
  static Color fastColor = Color.fromRGBO(58, 177, 151, 1);
  static Color errorColor = Color.fromRGBO(190, 190, 200, 1);

  static Color getCurrentRateColor({required String currentRate})  {
    Color _currentColor = Color.fromRGBO(190, 190, 200, 1);
    if (int.parse(currentRate) == 0) {
      _currentColor = NodeRateUtils.errorColor;
    }
    if (int.parse(currentRate) > 0) {
      _currentColor = NodeRateUtils.fastColor;
    }
    if (int.parse(currentRate) >= 200) {
      _currentColor = NodeRateUtils.mediumColor;
    }
    if (int.parse(currentRate) >= 1000) {
      _currentColor = NodeRateUtils.slowColor;
    }

    return _currentColor;
  }

  // static Future<(int, Color)> getCurrentRateInfo(String url,
  //     {int chainId = 1}) async {
  //   int _currentRate = 0;
  //   Color _currentColor = Color.fromRGBO(190, 190, 200, 1);
  //
  //   _currentRate = await NodeRateUtils.getResponseTime(url);
  //
  //   if (_currentRate == 0) {
  //     _currentColor = NodeRateUtils.errorColor;
  //   }
  //   if (_currentRate > 0) {
  //     _currentColor = NodeRateUtils.fastColor;
  //   }
  //   if (_currentRate >= 200) {
  //     _currentColor = NodeRateUtils.mediumColor;
  //   }
  //   if (_currentRate >= 1000) {
  //     _currentColor = NodeRateUtils.slowColor;
  //   }
  //
  //   return (_currentRate, _currentColor);
  // }

  static Future<(String,String)> getBlockHeightAndRate(String url,String chainName) async {
    final startTime = DateTime.now();
    int blockHeight = 0;
    try {
      if(chainName.toUpperCase()=='TRON'){
        blockHeight = await TronWeb3.getBlockHeightByRpc(url);
      }else if(chainName.toUpperCase()=='SOLNAN' || chainName.toUpperCase()=='SOLANA'){
        blockHeight = await SolanaWeb3.getBlockHeightByRpc(url);
      }else{
        blockHeight = await FlutterWeb3.getERC20BlockHeightByRpc(url);
      }
      kaiPrint('${chainName.toUpperCase()} url: ${url} blockheight: $blockHeight');
      final endTime = DateTime.now();
      final int milliseconds = endTime.difference(startTime).inMilliseconds;
      return (milliseconds.toString(),blockHeight.toString());
    } catch (e) {
      final endTime = DateTime.now();
      final int milliseconds = endTime.difference(startTime).inMilliseconds;
      return (milliseconds.toString(),blockHeight.toString());
    }
  }

  static Future<int> getResponseTime(String url,String chainName) async {
    final startTime = DateTime.now();
    try {
      if(chainName.toUpperCase()=='TRON'){
        await TronWeb3.getBlockHeightByRpc(url);
      }else if(chainName.toUpperCase()=='SOLNAN' || chainName.toUpperCase()=='SOLANA'){
        await SolanaWeb3.getBlockHeightByRpc(url);
      }else{
        await FlutterWeb3.getERC20BlockHeightByRpc(url);
      }
      // await http.head(Uri.parse(url)).timeout(const Duration(seconds: 2));
      final endTime = DateTime.now();
      final int milliseconds = endTime.difference(startTime).inMilliseconds;
      return milliseconds;
    } catch (e) {
      kaiPrint('getResponseTime ::::: $e');
      return 0;
    }
  }
}

// 钱包检测状态类
class WalletCheckStatus {
  late bool localpass;
  late bool serverpass;
  late bool googlepass;
  late bool icloudpass;
  late bool serverIsUpload;
  late bool cloudIsUpload;
  late bool isGoogleOverTimeAuth; // 是否授权过期
  late bool isIcloudOverTimeAuth;
  late Map<String, String?> keyMap;

  WalletCheckStatus(
      {Map<String, String?>? keyMap,
      bool isGoogleOverTimeAuth = false,
      bool isIcloudOverTimeAuth = false,
      bool serverIsUpload = true,
      bool cloudIsUpload = true,
      bool localpass = false,
      bool serverpass = false,
      bool googlepass = false,
      bool icloudpass = false}) {
    this.localpass = localpass;
    this.serverpass = serverpass;
    this.googlepass = googlepass;
    this.icloudpass = icloudpass;
    this.serverIsUpload = serverIsUpload;
    this.cloudIsUpload = cloudIsUpload;
    if (keyMap != null) {
      this.keyMap = keyMap;
    }
  }

  @override
  String toString() {
    // TODO: implement toString
    return '{localpass:$localpass,'
        'serverpass:$serverpass,'
        'googlepass:$googlepass,'
        'icloudpass:$icloudpass,'
        'keyMap:$keyMap,'
        'serverIsUpload:$serverIsUpload,'
        'cloudIsUpload:$cloudIsUpload,'
        'cloudIsUpload:$cloudIsUpload,}';
  }
}

// 异常状态
enum walletErrorStatus {
  serverNotUpload, //  服务端未上传
  cloudNotUpload, //  云端未上传
  localError, // 本地异常
  serverError, // 服务端异常
  googleError, // google异常
  icloudError, // icloud异常
  cloudError, // cloud异常 （包含google和icloud）
  localAndCloudError, // 本地和cloud异常
  localAndServerError, // 本地和服务端异常
  cloudAndServerError, // cloud和服务端异常
}

//上传枚举
enum walletUploadStatus {
  serverNotUpload, //  服务端未上传
  cloudNotUpload, //  云端未上传
}

// 备份枚举
enum walletResetStatus {
  localError, // 本地异常
  serverError, // 服务端异常
  googleError, // google异常
  icloudError, // icloud异常
  cloudError, // cloud异常 （包含google和icloud）
}

enum walletDestoryStatus {
  localAndCloudError, // 本地和cloud异常
  localAndServerError, // 本地和服务端异常
  cloudAndServerError, // cloud和服务端异常
}

//授权绑定获取文件状态
enum authGetDocStatus {
  emailEmpty, //没有绑定
  emailNotEqual, //不相等
  success, //成功
  noData, //没有找到云端数据
  cancel //取消了授权
}

class WalletCheck {
  Map<String, String?> walletKeyMap = {};
  WalletCheckStatus? walletStatus = null;

  static final WalletCheck _instance = WalletCheck._fatoryInit();

  factory WalletCheck() {
    return _instance;
  }

  WalletCheck._fatoryInit();

  // 钱包信息
  static Wallet? getWalletInfo() {
    // BuildContext context = NavKey.getContext();
    // Wallet? wallet = context.read<WalletInfoNotifier>().wallet;
    final userId = NativeChannelBridge.instance.appCommMsg?.userId;
    return ObjectBox().walletModel.getWalletByUId(userId!);
  }

  // 获取本地所有分片（包含未上传的时候）
  static List<String> getkeyList() {
    List<String> keyList =
        getWalletInfo() != null ? getWalletInfo()!.key.split(',') : [];
    return keyList;
  }

  // 本地分片key
  static String getLocalKey() {
    List<String> keyList =
        getWalletInfo() != null ? getWalletInfo()!.key.split(',') : [];
    if (keyList.length > 0) {
      return keyList[0];
    }
    return '';
  }

  // 服务端分片key
  static Future<(String, authGetDocStatus)> getServerKey() async {
    try {
      // 设置请求头
      var resp = (await HttpManager().get(API.getMpcSlice, {"wallet_id": '1'}));
      if (resp!.code != HttpConfig().successCode) {
        throw Exception('Failed to obtain server-side shards.');
      }
      if (resp.data['mpc'] == null || resp.data['mpc'].length <= 0) {
        return ('', authGetDocStatus.noData);
      }
      return (resp.data['mpc'].toString(), authGetDocStatus.success);
    } catch (e) {
      kaiPrint('object $e');
      return ('', authGetDocStatus.noData);
    }
  }

  // 云端分片 google

  static Future<(String, String, authGetDocStatus)> getGoogleKey() async {
    try {
      kaiPrint('getGoogleKey star');
      var _email = NativeChannelBridge.instance.appCommMsg?.google_email;
      if (_email == null || _email.isEmpty) {
        return ('', '', authGetDocStatus.emailEmpty);
      }
      kaiPrint('startGoogleLogin');
      var result = await LibCloudStorage.startGoogleLogin();
      kaiPrint('result=${result}');
      if (result.email.isEmpty) {
        return ('', '', authGetDocStatus.cancel);
      }
      kaiPrint('result.email.trim()  ${result.email.trim()}');
      kaiPrint('_email.trim()  ${_email.trim()}');
      if (result.email.trim() != _email.trim())
        return ('', '', authGetDocStatus.emailNotEqual);
      kaiPrint('_email  $_email');
      String? fileID = await googleDownLoadFileID(_email);
      kaiPrint('fileID  $fileID');
      //如果是空的话，就是没有上传
      if (fileID == null) return ('', '', authGetDocStatus.noData);
      String key =
          await LibCloudStorage.googleCloudDownloadFile(_email, fileID);
      kaiPrint('key :::::: $key');
      kaiPrint('key :::::: ${key.length}');
      return (key, fileID, authGetDocStatus.success);
    } catch (e) {
      kaiPrint('getGoogleKey catch = ${e}');

      return ('', '', authGetDocStatus.cancel);
    }
  }

  //直接拿整个列表，判断是不是有分片
  static Future<String?> googleDownLoadFileID(String email) async {
    String? fileID;
    var salt = SP().getRandomSalt() ?? "";
    kaiPrint('googleDownLoadFileID++++++  $salt ');
    try{
      String? serverKey = (await WalletCheck.getServerKey()).$1;
      kaiPrint('serverKey.isNotEmpty ${serverKey.isNotEmpty}');
      if(serverKey.isNotEmpty){
        salt = await HttpChainList().getSaltByUrl() ?? '';
      }
      kaiPrint('the last salt is $salt');
    }catch(e){
      kaiPrint('catch error : $salt');
    }
    try {
      // todo 需要跟uid做
      // await LibCloudStorage.startGoogleLogin();
      fileID =
          NavKey.getContext().read<WalletInfoNotifier>().wallet!.googleFileId;
      if (fileID == null) {
        FileList mpcList = await LibCloudStorage.queryGoogleDriveList(email);
        String uid = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
        GoogleDriveFile mpc = mpcList.dataList.firstWhere(
            (element) => element.fileName.contains('${uid}_${salt}'));
        fileID = mpc.fileId;
      }
    } catch (e) {}

    return fileID;
  }

  // icloud分片私钥
  static Future<(String, authGetDocStatus)> getIcloudKey() async {
    var apple_user_id = NativeChannelBridge.instance.appCommMsg!.apple_user_id;
    if (apple_user_id == null || apple_user_id!.isEmpty) {
      return ('', authGetDocStatus.emailEmpty);
    }

    String uid = NativeChannelBridge.instance.appCommMsg!.userId;
    String salt = SP().getRandomSalt() ?? '';
    kaiPrint('LibAppleAuthStorage start');
    var result = await LibAppleAuthStorage.login();
    kaiPrint('LibAppleAuthStorage end');
    kaiPrint('ios result = ${result}');
    if (result == null) {
      return ('', authGetDocStatus.cancel);
    }
    if (result.userID != apple_user_id) {
      return ('', authGetDocStatus.emailNotEqual);
    }
    kaiPrint('params uid:${uid} --salt${salt}');
    var content = await LibAppleAuthStorage.getStorageContent(uid, salt);
    if (content == null || content.isEmpty) {
      return ('', authGetDocStatus.noData);
    }
    return (content, authGetDocStatus.success);
  }

  // 检测异常状态
  Future<walletErrorStatus> checkWalletStatus(
      {WalletCheckStatus? walletCheckStatus, bool checkUpload = true}) async {
    if (walletCheckStatus == null) {
      walletCheckStatus = await checkWalletException();
    }
    kaiPrint('Future<walletErrorStatus> checkWalletStatus $walletCheckStatus');
    if (checkUpload) {
      // 服务端没有上传
      if (!walletCheckStatus.serverIsUpload) {
        return walletErrorStatus.serverNotUpload;
      }

      // 云端未上传
      if (!walletCheckStatus.cloudIsUpload) {
        return walletErrorStatus.cloudNotUpload;
      }
    }

    // 本地和服务端异常
    if (!walletCheckStatus.localpass && !walletCheckStatus.serverpass) {
      return walletErrorStatus.localAndServerError;
    }
    // 本地和云端异常
    if (!walletCheckStatus.localpass &&
        !walletCheckStatus.icloudpass &&
        !walletCheckStatus.googlepass) {
      return walletErrorStatus.localAndCloudError;
    }
    // 云端和服务端
    if (!walletCheckStatus.serverpass &&
        !walletCheckStatus.icloudpass &&
        !walletCheckStatus.googlepass) {
      return walletErrorStatus.cloudAndServerError;
    }

    // 本地异常
    if (!walletCheckStatus.localpass) {
      return walletErrorStatus.localError;
    }
    // 服务端异常
    if (!walletCheckStatus.serverpass) {
      return walletErrorStatus.serverError;
    }
    // 云端异常
    if (!walletCheckStatus.icloudpass && !walletCheckStatus.googlepass) {
      return walletErrorStatus.cloudError;
    }
    return walletErrorStatus.localError;
  }

  // 检测三片是否都通过
  Future<bool> checkWalletAllPass(
      {WalletCheckStatus? walletCheckStatus}) async {
    if (walletCheckStatus == null) {
      walletCheckStatus = await checkWalletException();
    }
    if (walletCheckStatus.localpass &&
        walletCheckStatus.serverpass &&
        (walletCheckStatus.googlepass || walletCheckStatus.icloudpass)) {
      return true;
    }
    return false;
  }

  //  签名前的验证
  static Future<List<String>> checkSignKey() async {
    List<String> resKeyList = [];
    List<String> keyList = getkeyList();
    int len = keyList.length;
    if (len >= 2) {
      // 进行检测
      if (await mpcTool().verifyMPCFragment(keyList[0]) == 1) {
        resKeyList.add(keyList[0]);
      }
      if (await mpcTool().verifyMPCFragment(keyList[1]) == 1) {
        resKeyList.add(keyList[1]);
      }
      if (len == 3) {
        if (await mpcTool().verifyMPCFragment(keyList[2]) == 1) {
          resKeyList.add(keyList[2]);
        }
      }
    } else {
      String serverKey = (await getServerKey()).$1;
      if (len == 1 && await mpcTool().verifyMPCFragment(keyList[0]) == 1) {
        resKeyList.add(keyList[0]);
      }
      if (serverKey.isNotEmpty &&
          await mpcTool().verifyMPCFragment(serverKey) == 1) {
        resKeyList.add(serverKey);
      } else {
        // 云端的key
        var googleKey = (await getGoogleKey()).$1;
        if (googleKey.isNotEmpty &&
            await mpcTool().verifyMPCFragment(googleKey) == 1) {
          resKeyList.add(googleKey);
        } else {
          // 如果是苹果设备
          if (Platform.isIOS &&
              NativeChannelBridge.instance.appCommMsg!.isAppleEnterprise ==
                  false) {
            String icloudKey = (await getIcloudKey()).$1;
            if (icloudKey.isNotEmpty &&
                await mpcTool().verifyMPCFragment(icloudKey) == 1) {
              resKeyList.add(icloudKey);
            }
          }
        }
      }
    }
    return removeDuplicates(resKeyList);
  }

//去重
  static List<T> removeDuplicates<T>(List<T> list) {
    Set<T> uniqueSet = Set<T>.from(list);
    List<T> uniqueList = uniqueSet.toList();
    return uniqueList;
  }

  // 感叹号提示检测
  Future<WalletCheckStatus> checkWalletExceptionLocal() async {
    WalletCheckStatus walletCheckStatus = WalletCheckStatus();
    // String localKey = '';
    // 本地分片
    int len = getkeyList().length;
    if (len > 0) {
      Wallet? walletInfo = getWalletInfo();
      // int localKeyStatus = await mpcTool().verifyMPCFragment(localKey);
      // if (localKeyStatus == 1) walletCheckStatus.localpass = true;
      if (len == 1) {
        if (walletInfo!.type == 2) {
          walletCheckStatus.serverIsUpload = true;
          String? appleUserId =
              NativeChannelBridge.instance.appCommMsg?.apple_user_id;
          String? googleEmail =
              NativeChannelBridge.instance.appCommMsg?.google_email;
          if (googleEmail != null && googleEmail.isNotEmpty) {
            walletCheckStatus.cloudIsUpload = true;
          } else {
            walletCheckStatus.cloudIsUpload = false;
          }
          if (Platform.isIOS &&
              (appleUserId != null && appleUserId.isNotEmpty)) {
            walletCheckStatus.cloudIsUpload = true;
          } else {
            walletCheckStatus.cloudIsUpload = walletCheckStatus.cloudIsUpload;
          }
        } else {
          walletCheckStatus.serverIsUpload = true;
          walletCheckStatus.cloudIsUpload = true;
        }
      }
      if (len == 2) {
        walletCheckStatus.serverIsUpload = true;
        walletCheckStatus.cloudIsUpload = false;
      }
      if (len == 3) {
        if (getkeyList()[1].isEmpty) {
          walletCheckStatus.cloudIsUpload = true;
          walletCheckStatus.serverIsUpload = false;
        } else {
          walletCheckStatus.serverIsUpload = false;
          walletCheckStatus.cloudIsUpload = false;
        }
      }
    }

    // if ((!walletCheckStatus.cloudIsUpload ||
    //     !walletCheckStatus.serverIsUpload)) {
    //   walletCheckStatus.keyMap = setLoadKey(localKey: localKey);
    // }

    return walletCheckStatus;
  }

  // 检测钱包异常 (任何一片)
  Future<WalletCheckStatus> checkWalletException(
      {bool checkUpload = true}) async {
    WalletCheckStatus walletCheckStatus = WalletCheckStatus();
    String localKey = '';
    String serverKey = '';
    String googleKey = '';
    String icloudKey = '';
    // 本地分片
    int len = getkeyList().length;
    if (len > 0) {
      localKey = getLocalKey();
      int localKeyStatus = await mpcTool().verifyMPCFragment(localKey);
      if (localKeyStatus == 1) walletCheckStatus.localpass = true;
      if (len == 1) {
        walletCheckStatus.serverIsUpload = true;
        walletCheckStatus.cloudIsUpload = true;
      }
      if (len == 2) {
        walletCheckStatus.serverIsUpload = true;
        walletCheckStatus.cloudIsUpload = false;
      }
      if (len == 3) {
        if (getkeyList()[1].isEmpty) {
          walletCheckStatus.cloudIsUpload = true;
          walletCheckStatus.serverIsUpload = false;
        } else {
          walletCheckStatus.serverIsUpload = false;
          walletCheckStatus.cloudIsUpload = false;
        }
      }
    }
    if ((!walletCheckStatus.cloudIsUpload ||
            !walletCheckStatus.serverIsUpload) &&
        checkUpload) {
      walletCheckStatus.keyMap = setLoadKey(localKey: localKey);
      walletKeyMap = walletCheckStatus.keyMap;
      walletStatus = walletCheckStatus;
      return walletCheckStatus;
    }

    // 服务端
    try {
      serverKey = (await getServerKey()).$1;
      if (serverKey.isNotEmpty) {
        walletCheckStatus.serverIsUpload = true;
      }
      int serverKeyStatus = await mpcTool().verifyMPCFragment(serverKey);
      if (serverKeyStatus == 1) {
        walletCheckStatus.serverpass = true;
      }
    } catch (e) {
      if (true) {}
    }

    // icloud云端
    try {
      String? appleUserId =
          NativeChannelBridge.instance.appCommMsg?.apple_user_id;
      if (appleUserId != null && appleUserId.isNotEmpty) {
        if (Platform.isIOS &&
            NativeChannelBridge.instance.appCommMsg!.isAppleEnterprise ==
                false) {
          icloudKey = (await getIcloudKey()).$1;
          if (icloudKey.isNotEmpty) {
            walletCheckStatus.cloudIsUpload = true;
          }
          int icloudKeyStatus = await mpcTool().verifyMPCFragment(icloudKey);
          if (icloudKeyStatus == 1) {
            walletCheckStatus.icloudpass = true;
          }
        }
      } else {
        walletCheckStatus.cloudIsUpload = false;
      }
    } catch (e) {
      // walletCheckStatus.isIcloudOverTimeAuth = true;
    }

    // google云端
    // todo ios设置没有谷歌邮箱的情况
    try {
      String? googleEmail =
          NativeChannelBridge.instance.appCommMsg?.google_email;
      kaiPrint('googleEmail?  $googleEmail');
      if (googleEmail != null && googleEmail.isNotEmpty) {
        googleKey = (await getGoogleKey()).$1;
        kaiPrint('googleKey?  $googleKey');
        if (googleKey.isNotEmpty) {
          walletCheckStatus.cloudIsUpload = true;
        }
        int googleKeyStatus = await mpcTool().verifyMPCFragment(googleKey);
        kaiPrint('googleKeyStatus?  $googleKeyStatus');
        if (googleKeyStatus == 1) {
          walletCheckStatus.googlepass = true;
        }
      } else {
        walletCheckStatus.cloudIsUpload = false;
      }
    } catch (e) {
      //  walletCheckStatus.isGoogleOverTimeAuth = true;
    }
    Map<String, String?> keyMap = setLoadKey(
        serverKey: serverKey,
        googleKey: googleKey,
        icloudKey: icloudKey,
        localKey: localKey);
    walletCheckStatus.keyMap = keyMap;
    try {
      // 观察 者 钱包 本地 必 报错
      if (len > 0 && getWalletInfo()?.type == 2) {
        walletCheckStatus.localpass = false;
        walletCheckStatus.serverpass = true;
      }
    } catch (e) {}

    walletKeyMap = keyMap;
    walletStatus = walletCheckStatus;
    return walletCheckStatus;
  }

// 设置key
  static Map<String, String?> setLoadKey(
      {String? serverKey,
      String? googleKey,
      String? icloudKey,
      String? localKey}) {
    Map<String, String?> keyMap = {};
    keyMap['serverKey'] = serverKey;
    keyMap['googleKey'] = googleKey;
    keyMap['icloudKey'] = icloudKey;
    keyMap['localKey'] = localKey;
    return keyMap;
  }

  // 返回非空的key
  static Map<String, String?> resValueKey(Map<String, String?> keyMap) {
    String? serverKey = keyMap['serverKey'];
    String? googleKey = keyMap['googleKey'];
    String? icloudKey = keyMap['icloudKey'];
    String? localKey = keyMap['localKey'];
    Map<String, String?> resMap = {};
    if (serverKey != null && serverKey.isNotEmpty) {
      resMap['serverKey'] = serverKey;
    }
    if (googleKey != null && googleKey.isNotEmpty) {
      resMap['googleKey'] = googleKey;
    }
    if (icloudKey != null && icloudKey.isNotEmpty) {
      resMap['icloudKey'] = icloudKey;
    }
    if (localKey != null && localKey.isNotEmpty) {
      resMap['localKey'] = localKey;
    }
    return resMap;
  }

  // 弹窗
  static Future showErrorDialog(
      {DialogType? callBackStatus, Function? callBack}) async {
    BuildContext context = NavKey.getContext();
    try {
      //未设置密码>钱包异常>未上传云端>token过期
      if (callBackStatus == null) {
        return;
      }
      kaiPrint('callBackStatus $callBackStatus');
      return Utils.showBottomSheetDialog(
          context,
          KaiBottomTipDialog(
            type: callBackStatus,
            Confirm: () {
              // 忘记密码 提示弹出层
              if (DialogType.PASSWORD == callBackStatus) {
                return Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => SetPassPage(
                            type: '4',
                          )),
                );
              }
              // 风险 提示弹出层
              if (callBackStatus == DialogType.RISK_SECURITY) {
                return Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => WalletMPCSecurityManager(
                            pageType: MPCManagerPageType.Security,
                          )),
                ).then((value) {
                  callBack != null ? callBack!() : '';
                });
              }
              //
              // 钱包检测异常 即 单片 异常情况   提示弹出层
              // 销毁 钱包
              // DELETE_WALLET,
              // 服务端 异常
              // SERVER_SIDE_ERROR,
              // 云端异常
              // CLOUD_SIDE_ERROR,
              if ([
                DialogType.WALLET_ERROR,
                DialogType.SERVER_SIDE_ERROR,
                DialogType.CLOUD_SIDE_ERROR
              ].contains(callBackStatus)) {
                return Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => WalletMPCSecurityManager(
                            pageType: MPCManagerPageType.Recast,
                          )),
                ).then((value) {
                  callBack != null ? callBack!() : '';
                });
              }
              // 销毁钱包
              if (callBackStatus == DialogType.DELETE_WALLET) {
                return Utils.showBottomSheetDialog(context, DeleteWallet()).then((value) {
                  bool isLast = !Navigator.canPop(NavKey.getContext());
                  if(!isLast){
                    Navigator.pop(NavKey.getContext());
                  }
                });
              }
            },
          ));
    } catch (e) {
      kaiPrint(e);
    }
  }

// 弹出 获取 云盘的 弹出层
}
